package com.qf.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.timeout.ReadTimeoutHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class NettyServer {

    private EventLoopGroup master = new NioEventLoopGroup();
    private EventLoopGroup slave = new NioEventLoopGroup();

    @Value("${server.port}")
    private int port;

    @Autowired
    private List<ChannelHandler> channelHandlers;

    /**
     * 初始化一个Netty WebSocket服务端
     */
    public void init(){

        ServerBootstrap bootstrap = new ServerBootstrap()
                .group(master, slave)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();

                        //添加过滤器链
                        pipeline.addLast(new HttpServerCodec());
                        pipeline.addLast(new HttpObjectAggregator(1024 * 1024 * 10));
                        pipeline.addLast(new WebSocketServerProtocolHandler("/"));
                        pipeline.addLast(new ReadTimeoutHandler(2, TimeUnit.MINUTES));
                        //自定义的channelhandler

                        pipeline.addLast(channelHandlers.toArray(new ChannelHandler[0]));
                    }
                });

        ChannelFuture future = bootstrap.bind(port);
        try {
            future.sync();
            System.out.println("Netty服务器启动成功....");
        } catch (InterruptedException e) {
            e.printStackTrace();
            master.shutdownGracefully();
            slave.shutdownGracefully();
        }
    }

}
